package Wix::Harvest;

use Digest::MD5 qw/md5_hex/;
use File::Find;
use File::Spec;
use File::Basename;
use Wix::Tag::Component;
use Wix::Tag::ComponentGroup;
use Wix::Tag::Directory;
use Wix::Tag::DirectoryRef;
use Wix::Tag::File;
use Wix::Tag::Shortcut;
use Carp;

use strict;

sub new(;$) {
	my ($class, $obj) = @_;
	
	if ($obj) {
		return bless($obj, $class);
	}
	else {
		return bless({}, $class);
	} 
}

sub getDirectory() {
	my ($self) = @_;
	
	return $self->{_DIRECTORY};
}

sub getComponentGroup() {
	my ($self) = @_;
	
	return $self->{_COMPONENT_GROUP};
}

sub Harvest($) {
	my ($fref) = @_;
	
	my ($dir, $ignoreroot) = ($fref->{SRC}, $fref->{NOROOT});
	
	unless (-d $dir) {
		croak sprintf('Cannot open directory "%s"', $dir);
	}	
		
	my $root_dir = File::Spec->rel2abs($dir);
	my $root_dir_digest = md5_hex($root_dir);	
	
	my $dirs = {};
	
	my $componentgroup = Wix::Tag::ComponentGroup->new(
		{
			ID => sprintf('COMPONENTGROUP_%s', uc basename($root_dir))
		}
	);
	
	my $harvester = Wix::Harvest->new();
	$harvester->{_DIRECTORY} = Wix::Tag::DirectoryRef::GetApplicationRoot();
	$dirs->{$root_dir_digest} = $harvester->{_DIRECTORY};
	
	find(
		sub {
			foreach ($File::Find::name, $File::Find::dir) {
				s/\//\\/g;	
			}	
					
			if ($ignoreroot && $root_dir eq $File::Find::name) {
				return;
			}
			
			my $digest = md5_hex($File::Find::name);			
			my $parent_digest = md5_hex($File::Find::dir);
			
			my $name = basename(File::Spec->rel2abs($_));
						
			my $parentdirectory = $dirs->{$parent_digest};
			
			if (-d $File::Find::name) {
				my $directory = Wix::Tag::Directory->new(
					{
						ID => sprintf('DIR_%s', $digest),
						NAME => $name
					}
				);
			
				$dirs->{$digest} = $directory;
			
				$parentdirectory->addDirectory($directory);	
			} 
			else {
				my $file = Wix::Tag::File->new(
					{
						ID => sprintf('FILE_%s', $digest),
						NAME => $name,
						SOURCE => $File::Find::name
					}
				);
				
				foreach (qw/START DESKTOP/) {
					if (defined(my $ref = $fref->{SHORTCUTS}->{$_}->{$File::Find::name}->{DIRECTORYREF})) {
						$file->addShortcut(
							Wix::Tag::Shortcut->new(
								{
									ID => sprintf('%sLINK_%s', $_, $digest),
									NAME => $name,
									DIRECTORY => $ref,
									WORKINGDIRECTORY => $parentdirectory->getAttr('Id'),
									ADVERTISE => 'yes'
								}
							)
						);
					}	
				}
				
				my $component = Wix::Tag::Component->new(
					{
						ID => sprintf('COMPONENT_%s', $digest)
					}
				);
				
				$component->addFile($file);
				
				$componentgroup->addComponentRef($component->getComponentRef());
			
				$parentdirectory->addComponent($component);	
			}
		},
		$root_dir
	);
	
	$harvester->{_COMPONENT_GROUP} = $componentgroup;
	
	return $harvester;
}

1;